<?php
/**
 * Controller for Private Sale campaign
 * @author Nghia Nguyen <quangnghia@happyliving.vn - 0903.755.645>
 *
 **/
class MController extends Controller
{
    protected $mc;
    public $page;

    /**
     * Init MailChimp API
     *
     * @author Nghia Nguyen <quangnghia@happyliving.vn - 0903.755.645>
     **/
    public function init()
    {
        try {
            // Happy Living API Key
            $this->mc = new Mailchimp('3e3bc7211c1d284592886a43d00398eb-us5');
        } catch (Mailchimp_Error $e) {
            throw new Exception("You have not set an API key. Please set it in MController");
        }
    }

    /**
     * Homepage
     *
     * @author Nghia Nguyen <quangnghia@happyliving.vn - 0903.755.645>
     **/
    public function actionIndex($ref_id=false)
    {
        $this->pageTitle = 'Thương hiệu đẳng cấp';
        $this->page = 'subscribe';
        $gioithieu_id = 0;

        if($ref_id)
        {
            $gioithieu = User::model()->findByPk((int)$ref_id);
            if($gioithieu !== NULL) $gioithieu_id = $gioithieu->id;
        }

        $this->render('index', array('gioithieu_id'=>$gioithieu_id));
    }

    /**
     * Hook for MailChimp to update user status from 0 to 1
     *
     * @author Nghia Nguyen <quangnghia@happyliving.vn - 0903.755.645>
     **/
    public function actionHook()
    {
        if($_POST['type'] == "subscribe") {
            $data = $_POST['data'];

            $criteria = new CDbCriteria;
            $criteria->condition = 'email=:email';
            $criteria->params = array(':email'=>$data['email']);
            $user = User::model()->find($criteria);
            if($user)
            {
                $user->status = User::ACTIVE;
                $user->update_time = time();
                $user->update(array('status', 'update_time'));
            }
        }
    }

    /**
     * Ajax call to create user before submit form
     *
     * @author Nghia Nguyen <quangnghia@happyliving.vn - 0903.755.645>
     **/
    public function actionCreateSession()
    {
        // create cookies
        $user = new User;
        $user->email = $_POST["email"];
        $user->referral_id = $_POST["ref_id"];
        $user->customer_name = $_POST["fname"];
        $user->mobile = $_POST["mobile"];
        $user->status = User::INACTIVE;
        $user->create_time = time();
        $user->generateActivateCode();
        $user->save();
        var_dump($user->errors);
    }

    /**
     * Landing page for Mailchimp to redirect to
     *
     * @author Nghia Nguyen <quangnghia@happyliving.vn - 0903.755.645>
     **/
    public function actionComplete()
    {
        $this->pageTitle = 'Hoàn tất đăng ký';
        $this->page = 'complete';

        if(isset(Yii::app()->request->cookies['email'])){
            $email = Yii::app()->request->cookies['email']->value;
        // $email = Yii::app()->session['email'];
        }else{
            $this->redirect(array("/m/index"));
        }

        $user = User::model()->findByAttributes(array('email'=>$email));

        if($user === NULL)
        {
            Yii::log('error', 'No user found. Email: ' . $email);
            $this->redirect(array("/m/index"));
        }
        else
            $referral_id = $user->id;

        $this->render("complete", array("referral_id"=>$referral_id));
    }

    /**
     * Member list and Winner list page
     *
     * @author Nghia Nguyen <quangnghia@happyliving.vn - 0903.755.645>
     **/
    public function actionResult()
    {
        $this->pageTitle = 'Danh sách thành viên';
        $user_member = new CActiveDataProvider('User', array(
            'criteria'=>array(
                'condition'=>'status='.User::ACTIVE,
                'order'=>'create_time DESC',
            ),
            'pagination'=>array('pageSize'=>20),
        ));		$condition='';
		if(!empty($_POST["datepicker"])){			$condition='SUBSTRING(update_time,1,10) = \''.$_POST["datepicker"].'\'';		}		
        $winner = new CActiveDataProvider('Winner', array(
            'criteria'=>array(				'condition'=>$condition,
                'order'=>'update_time DESC',
            ),
            'pagination'=>array('pageSize'=>20),
        ));        $this->render("result", array('user_member'=>$user_member, 'winner'=>$winner));
    }

    /**
     * Scree for customers to retrieve their referral URL
     *
     * @author Nghia Nguyen <quangnghia@happyliving.vn - 0903.755.645>
     **/
    public function actionProfile()
    {
        $this->pageTitle = 'Tài khoản của bạn';

        $name = 'Tên';
        $email = 'Email';
        $referral_id = 0;
        $referral_link = "";
        $check = 0;
        if(isset($_POST["email"]))
        {
            $criteria = new CDbCriteria;
            $criteria->condition = "email=:email";
            $criteria->params = array(":email"=>$_POST["email"]);

            $user = User::model()->find($criteria);
            if($user !== NULL)
            {
                $name = $user->customer_name;
                $email = $user->email;
                $referral_id = $user->id;
                 $referral_link = Yii::app()->createAbsoluteUrl('/m/index',array('ref_id'=>$referral_id));
            }
            else
            {
                $check = 1;
            }
        }
        $this->render("profile", array('referral_link'=>$referral_link,"referral_id"=>$referral_id, "email"=>$email, "name"=>$name, "check"=>$check));
    }

    /**
     * Term and condition page
     *
     * @author Nghia Nguyen <quangnghia@happyliving.vn - 0903.755.645>
     **/
    public function actionTheLe(){
        $this->pageTitle = 'Thể lệ chương trình';
        $this->render("theLe");
    }
    
}